#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <iostream>
#include<stdlib.h>
#include "time.h"
#include<string.h>
using namespace std;
using namespace cv;
int i=0,a=1;
int time_jishi=0;
int SHIPIN_Huanchong=1;
string outputVideoPath[11]={"savephoto/test1.avi","savephoto/test2.avi","savephoto/test3.avi","savephoto/test4.avi","savephoto/test5.avi","savephoto/test6.avi","savephoto/test6.avi","savephoto/test7.avi","savephoto/test8.avi","savephoto/test9.avi","savephoto/test10.avi"};
string getTime()
{
	time_t timep;
	time (&timep);
	char tmp[64];
	strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&timep) );
	return tmp;
}
void Pic2Gray(Mat camerFrame,Mat &gray)
{
	//普通台式机3通道BGR,移动设备为4通道
	if (camerFrame.channels() == 3)
	{
		cvtColor(camerFrame, gray, COLOR_BGR2GRAY);
	}
	else if (camerFrame.channels() == 4)
	{
		cvtColor(camerFrame, gray, COLOR_BGRA2GRAY);
	}
	else
		gray = camerFrame;
}
int main()
{
	//加载Haar或LBP对象或人脸检测器
	CascadeClassifier faceDetector;
	std::string faceCascadeFilename = "/home/wzx/face/haarcascade_frontalface_default.xml";
	//友好错误信息提示
	try{
		faceDetector.load(faceCascadeFilename);
	}
	catch (cv::Exception e){}
	if (faceDetector.empty())
	{
		std::cerr << "脸部检测器不能加载 (";
		std::cerr << faceCascadeFilename << ")!" << std::endl;
		exit(1);
	}
	//打开摄像头
	VideoCapture cap(0);
	int frameNum = 300;
	//获取当前摄像头的视频信息
	cv::Size sWH = cv::Size((int)cap.get(CAP_PROP_FRAME_WIDTH),
	(int)cap.get(CAP_PROP_FRAME_HEIGHT));
	while (true)
	{
		frameNum=300;
		time_jishi++;
		Mat camerFrame;
		cap >> camerFrame;
		if (camerFrame.empty())
		{
			std::cerr << "无法获取摄像头图像" << std::endl;
			camerFrame.release();
			getchar();
			
			exit(1);
		}
		Mat displayedFrame(camerFrame.size(),CV_8UC3);
		//人脸检测只试用于灰度图像
		Mat gray;
		Pic2Gray(camerFrame, gray);
		//直方图均匀化(改善图像的对比度和亮度)
		Mat equalizedImg;
		equalizeHist(gray, equalizedImg);
		int flags = CASCADE_SCALE_IMAGE;	//检测多个人
		Size minFeatureSize(60, 60);
		float searchScaleFactor = 1.3f;
		int minNeighbors = 2;
		std::vector<Rect> faces;
		faceDetector.detectMultiScale(equalizedImg, faces, searchScaleFactor, minNeighbors, flags, minFeatureSize);
		//画矩形框
		cv::Mat face;
		cv::Point text_lb;
		for (size_t i = 0; i < faces.size(); i++)
		{
			if (faces[i].height > 0 && faces[i].width > 0)
			{
				/****************画方框***************/
				face = gray(faces[i]);
				text_lb = cv::Point(faces[i].x, faces[i].y);
				cv::rectangle(equalizedImg, faces[i], cv::Scalar(255, 0, 0), 2, 8, 0);
				cv::rectangle(gray, faces[i], cv::Scalar(255, 0, 0), 2, 8, 0);
				cv::rectangle(camerFrame, faces[i], cv::Scalar(255, 0, 0), 2, 8, 0);
				/****************画方框完成***************/	
			}
		}
		imshow("直方图均匀化", equalizedImg);
		imshow("灰度化", gray);
		imshow("renlian", camerFrame);
		waitKey(20);
	}
	getchar();
	return 0;
}

